<template>
  <div style="width: 100%; height: 100%;" class="login-background">
    <el-row class="margin-top-log" :gutter="100">
      <el-col :span="6" :offset="9">
        <el-card shadow="always">
          <el-row>
            <div v-if="buttonStatus === 1" style="text-align: center">
              <el-avatar size="large" :src="this.$global.mediaHost + this.avatarUrl"></el-avatar>
            </div>
            <div v-else style="text-align: center">
              <label for="fileInput">
                <el-avatar size="large" :src="this.$global.mediaHost + this.avatarUrl"></el-avatar>
              </label>
              <input v-show="false" type="file" id="fileInput" accept="image/*" @change="uploadImage">
            </div>
          </el-row>
          <el-row v-show="buttonStatus===2">
            <el-input placeholder="请输入昵称" v-model="nickName"></el-input>
          </el-row>
          <el-row>
            <el-input placeholder="请输入用户名" v-model="userName" @blur="buttonStatus === 1 && userName !== '' ? loginAvatar() : ''"></el-input>
          </el-row>
          <el-row>
            <el-input placeholder="请输入密码" v-model="pwd" show-password></el-input>
          </el-row>
          <el-row v-show="buttonStatus===2">
            <el-input placeholder="请确认密码" v-model="confirmPwd" show-password></el-input>
          </el-row>
          <el-row class="text-center">
            <el-button type="primary" @click="buttonStatus === 1 ? login() : registered()">
              {{ buttonStatus === 1 ? '立即登录' : '立即注册' }}
            </el-button>
          </el-row>
          <el-row class="text-center">
            <el-link type="primary" :underline="false" @click="changeStatus()">
              {{ buttonStatus === 1 ? '前往注册' : '已有账号，快去登录' }}
            </el-link>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    return {
      userName: '',
      pwd: '',
      confirmPwd: '',
      nickName: '',
      avatarId: 1,
      paramsData: {},
      buttonStatus: 1,
      avatarUrl: this.$global.avatarDefault
    }
  },
  methods: {
    uploadImage: function (e) {
      console.log(e.target.files[0])
      if (e.target.files[0] !== undefined) {
        let fileName = e.target.files[0].name;
        let fileType = e.target.files[0].type;
        let imageType = this.$global.imageType
        if (!fileType.includes(imageType)) {
          this.$message.error({
            message: "文件类型错误",
            center: true,
            duration: 1000
          });
          return false;
        }
        fileName = "/"+ imageType +"/" + this.$global.randomStr(24) + fileName.substring(fileName.lastIndexOf("."))
        const OSS = require('ali-oss')
        const client = new OSS({
          bucket: this.$global.bucket,
          region: this.$global.region,
          secure: true,
          accessKeyId: this.$global.accessKeyId,
          accessKeySecret: this.$global.accessKeySecret,
        });
        const asyncThis = this
        async function put () {
          try {
            let loading = asyncThis.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading'
            });
            //object-name可以自定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至当前Bucket或Bucket下的指定目录。
            let result = await client.put(fileName, e.target.files[0]);
            console.log(result);
            loading.close();
            asyncThis.avatarUrl = fileName;
          } catch (e) {
            console.log(e);
          }
        }
        put();
      }
    },
    /*uploadImage: function (e) {
      console.log(e.target.files[0])
      if (e.target.files[0] !== undefined) {
        const data = new FormData();
        data.append("file",e.target.files[0])
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading'
        });
        this.$ajax({
          method: 'post',
          headers: {
            'Access-Control-Allow-Origin': '*',
            'Content-Type': 'multipart/form-data'
          },
          url: this.$global.host + '/v1/common/uploadImage',
          data: data
        }).then(response => {
          const responseData = response.data.data;
          const responseState = response.data.state
          loading.close();
          if (2000 === responseState.code) {
            this.mediaView=responseData.mediaView
          } else {
            this.$message.error({
              message: responseState.msg,
              center: true,
              duration: 1000
            });
          }
        }).catch(function (err) {
          console.log(err)
        })
      }
    },*/
    /**
     * 用户登录头像
     */
    loginAvatar: function () {
      if (this.$global.checkSpecificKey(this.userName)) {
        this.paramsData.userName = this.userName
        this.$ajax({
          method: 'post',
          headers: this.$global.headers,
          url: this.$global.host + '/v1/media/loginAvatar',
          data: JSON.stringify({
            "data": this.paramsData
          }),
        }).then(response => {
          const responseData = response.data.data;
          const responseState = response.data.state
          if (2000 === responseState.code) {
            if (responseData.mediaView !== null && this.buttonStatus === 1) {
              this.avatarUrl=responseData.mediaView.mediaUrl
            }else if (responseData.mediaView === null && this.buttonStatus === 1){
              this.avatarUrl = this.$global.avatarDefault
            }else {
              this.avatarUrl = this.$global.avatar
            }
          } else {
            this.$message.error({
              message: responseState.msg,
              center: true,
              duration: 1000
            });
          }
        }).catch(function (err) {
          console.log(err)
        })
      }
    },
    /**
     * 登录
     */
    login: function () {
      if (this.checkInput()) {
        this.paramsData.userName = this.userName
        this.paramsData.pwd = this.pwd
        this.$ajax({
          method: 'post',
          headers: this.$global.headers,
          url: this.$global.host + '/v1/user/login',
          data: JSON.stringify({
            "data": this.paramsData
          }),
        }).then(response => {
          const responseData = response.data.data;
          const responseState = response.data.state
          if (2000 === responseState.code) {
            this.$global.setUser(responseData.user)
            this.$global.setTeamId(responseData.teamId)
            this.$router.push({path: '/homePage'})
          } else {
            this.$message.error({
              message: responseState.msg,
              center: true,
              duration: 1000
            });
          }
        }).catch(function (err) {
          console.log(err)
        })
      }

    },
    /**
     * 注册
     */
    registered: function () {
      if (this.checkInput()) {
        this.paramsData.userName = this.userName
        this.paramsData.pwd = this.pwd
        this.paramsData.nickName = this.nickName
        this.paramsData.avatarUrl = this.avatarUrl
        this.$ajax({
          method: 'post',
          headers: {
            'Access-Control-Allow-Origin': '*',
            'Content-Type': 'application/json;charset=UTF-8'
          },
          url: this.$global.host + '/v1/user/registered',
          data: JSON.stringify({
            "data": this.paramsData
          }),
        }).then(response => {
          const responseData = response.data.data;
          const responseState = response.data.state
          if (2000 === responseState.code) {
            this.$global.setUser(responseData.user)
            this.$global.setTeamId(responseData.teamId)
            this.$router.push({path: '/homePage'})
          } else {
            this.$message.error({
              message: responseState.msg,
              center: true,
              duration: 1000
            });
          }
        }).catch(function (err) {
          console.log(err)
        })
      }
    },
    /**
     * 改变按钮状态
     */
    changeStatus: function () {
      if (this.buttonStatus === 1) {
        this.buttonStatus = 2
        this.avatarUrl = this.$global.avatar
      } else {
        this.buttonStatus = 1
        this.avatarUrl = this.$global.avatarDefault
      }
      this.userName = ''
      this.pwd = ''
      this.confirmPwd = ''
      this.nickName = ''
    },
    checkInput: function () {
      if (!this.$global.checkSpecificKey(this.userName + this.pwd + this.nickName + this.confirmPwd)) {
        this.$message.warning({
          message: '不允许输入特殊符号',
          center: true,
          duration: 1000
        });
        return false
      }
      if (this.userName.length < 5 || this.userName.length > 20) {
        this.$message.warning({
          message: '用户名必须输入5~20位字符',
          center: true,
          duration: 1000
        });
        return false;
      }
      if (this.pwd.length < 6 || this.pwd.length > 20) {
        this.$message.warning({
          message: '密码必须输入6~20位字符',
          center: true,
          duration: 1000
        });
        return false;
      }
      if (this.buttonStatus === 2 && (this.nickName.length < 1 || this.nickName.length > 10)) {
        this.$message.warning({
          message: '昵称必须输入1~20位字符',
          center: true,
          duration: 1000
        });
        return false;
      }

      if (this.buttonStatus === 2 && (this.confirmPwd.length < 6 || this.confirmPwd.length > 20 || this.pwd !== this.confirmPwd)) {
        this.$message.warning({
          message: '两次输入的密码不一致',
          center: true,
          duration: 1000
        });
        return false;
      }

      if (this.buttonStatus === 2 && this.avatarUrl === this.$global.avatar) {
        this.$message.warning({
          message: '请选择您的头像',
          center: true,
          duration: 1000
        });
        return false;
      }
      return true;
    }
  }
}
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
}

.el-col {
  border-radius: 4px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}

.text-center {
  text-align: center;
}

.margin-top-log {
  margin-top: 200px;
}
.login-background {
  position: fixed;
  top:0;
  left:0;
  /*以上三句是让整个span放在屏幕的最左上方*/
  height: 100%;
  width: 100%;
  /*以上两句实现全屏大小*/
  background: url("https://media.maixy.top/wode/b1.jpg") no-repeat center 0;/*引入背景图，不重复出现*/
  background-size:cover;/*图片随屏幕大小同步缩放,但是图片画面可能只显示一部分*/
}
</style>
